<?php

namespace common\modules\sms\models\frontend;

use daixianceng\smser\Smser;
use Exception;
use Yii;

class Event extends \common\modules\sms\models\Event
{

    /**
     * @inheritdoc
     */
    public function beforeSave($insert)
    {
        if (Customer::$current)
        {
            $this->service_id = 'luosimao'; // TODO 改成可动态配置
            $this->customer_id = Customer::$current->id;
            $this->created_by = Customer::$current->id;
            $this->updated_at = Customer::$current->id;
        }

        // 保存调用时的IP地址
        $this->server_ip = Yii::$app->request->userIP;

        // 默认就是发送成功?
        $this->status = self::STATUS_SUCCESS;

        // 发送咯
        return parent::beforeSave($insert);
    }

    /**
     * @inheritdoc
     */
    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);

        // 只有是插入记录并且没有错误时才提交
        if ($insert && empty($this->getErrors()))
        {
            /** @var Smser $sms */
            $sms = Yii::$app->get('sms-' . $this->service_id);

            try
            {
                $sms->send($this->mobile, $this->content);
            }
            catch (Exception $e)
            {
                Yii::warning("调用{$this->service_id}发送短信失败:" . json_encode([
                        'msg' => $e->getMessage(),
                        'code' => $e->getCode(),
                    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), __METHOD__);

                // 失败的话,要将状态设置为失败
                $this->status = self::STATUS_FAILED;
                $this->update(false); // 不做校验了
                return;
            }

            // 更新额度信息
            if (Customer::$current)
            {
                Customer::$current->updateCounters([
                    'quota_used' => 1,
                ]);
            }
        }
    }
}
